/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.googlecode.greenbridge.binder.excel;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.util.StringUtils;

/**
 *
 * @author U368337
 */
public class RangeChecker {


    /**
     * For a given test class, lookup a system propertery that specifies valid ranges.
     * eg. Class 'org.TestA' will look for a system property 'TestA-range'
     *
     * The string of the above system propery will be converted to a set of numbers.
     * if the row number provided is in that string, true will be returned.
     *
     * @param test
     * @param rowNumber
     * @return
     */
    public static boolean isInRange(Class test, int rowNumber) {
        System.out.println("Range checking: " + rowNumber );
        String range = System.getProperty(test.getSimpleName() + "-range");
        if (StringUtils.hasLength(range)) {
            Set<Integer> range_set = generateValidNumbers(range);
            if (range_set.contains(rowNumber)) return true;
            else return false;
        }
        return true; // default behavior
    }

    /**
     * Generates a list of valid numbers from an input string. Valid strings include:
     * '1,2,3,4,7,19'
     * '1-4,7,19'
     *
     * @param string a string.
     * @return a list of integers contained in the string.
     */
    public static Set<Integer> generateValidNumbers(String string) {
        Set<Integer> set = new HashSet<Integer>();
        String[] atoms = string.split(",");
        for (String atom : atoms) {
            List<Integer> numbers = parseAtom(atom);
            set.addAll(numbers);
        }
        return set;
    }

    /**
     * Parse an atom string of a range. Examples:
     * '1' = 1
     * '3-7' = 3,4,5,6,7
     * @param atom the atom, eg '3-7'
     * @return a list of integers, eg 3,4,5,6,7
     */
    protected static List<Integer> parseAtom(String atom) {
        List<Integer> numbers = new ArrayList<Integer>();
        if (atom.contains("-")) {
            String[] range = atom.split("-");
            int low  = Integer.parseInt(range[0]);
            int high = Integer.parseInt(range[1]);
            for (int i = low; i <= high; i++) {
                numbers.add(i);
            }
        }
        else {
            numbers.add(Integer.parseInt(atom));
        }
        return numbers;
    }




}
